package com.yxc.service;

import com.yxc.dao.BackendUserDao;
import com.yxc.dao.DevUserDao;
import com.yxc.dto.LoginUserDto;
import com.yxc.entity.BackendUser;
import com.yxc.entity.DevUser;
import com.yxc.utils.SessionUtils;
import com.yxc.vo.LoginUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class LoginUserService {

    @Autowired
    DevUserDao devUserDao;

    @Autowired
    BackendUserDao backendUserDao;

    public LoginUserVo login(LoginUserDto loginUserDto) {
        LoginUserVo vo = new LoginUserVo();
        if (loginUserDto.getLoginType() == 1){
            BackendUser backendUser = new BackendUser();
            backendUser.setUsercode(loginUserDto.getAccount());
            backendUser.setUserpassword(loginUserDto.getPassword());
            List<BackendUser> list = backendUserDao.queryAllBy(backendUser);
            if (list.size()==0){
                throw new RuntimeException("账号或密码错误");
            }
            vo.setUserName(loginUserDto.getAccount());
            vo.setUserCode("admin");

            StringBuilder token = new StringBuilder();
            String uuid = UUID.randomUUID().toString().replace("-","");
            token.append(uuid).append("-").append(list.get(0).getUsercode())
                    .append("-").append(list.get(0).getId())
                    .append("-admin-").append(System.currentTimeMillis());
            // uuid-userCode-id-admin-time
            vo.setToken(token.toString());
            SessionUtils.put(token.toString(),list.get(0));
            return vo;
        }else if (loginUserDto.getLoginType() == 2){
            DevUser devUser = new DevUser();
            devUser.setDevcode(loginUserDto.getAccount());
            devUser.setDevpassword(loginUserDto.getPassword());
            List<DevUser> list = devUserDao.queryAllBy(devUser);
            if (list.size()==0){
                throw new RuntimeException("账号或密码错误");
            }
            vo.setUserName(loginUserDto.getAccount());
            vo.setUserCode("dev");

            StringBuilder token = new StringBuilder();
            String uuid = UUID.randomUUID().toString().replace("-","");
            token.append(uuid).append("-").append(list.get(0).getDevcode())
                    .append("-").append(list.get(0).getId())
                    .append("-dev-").append(System.currentTimeMillis());
            // uuid-userCode-id-dev-time
            vo.setToken(token.toString());
            SessionUtils.put(token.toString(),list.get(0));
            return vo;
        }else {
            throw new RuntimeException("用户类型错误");
        }
    }
}
